import React, { Component } from "react";
import axios from 'axios';
import PubSub from 'pubsub-js';

export default class List extends Component {

    state = {
        heros: []
    }

    render() {
        return (
            <div className="hero-list">
                {this.state.heros.map((item) => {
                    return (
                        <div className="item" key={item.id}>
                            <img
                                width="100%"
                                src={"http://cdn.xiaohigh.com" + item.image}
                                alt=""
                            />
                            <p>{item.name}</p>
                        </div>
                    );
                })}
            </div>
        );
    }


    //发送请求
    // https://api.xiaohigh.com/heros?q=战士
    async componentDidMount(){
        let result = await axios.get('http://api.xiaohigh.com/heros');
        this.setState({
            heros: result.data
        });

        //组件挂载完毕, 订阅频道
        PubSub.subscribe('hero', async (name, data) => {
            //发送请求
            let result = await axios.get('http://api.xiaohigh.com/heros', {params: {q: data}});
            this.setState({
                heros: result.data
            });
        });
    }

    //收尾工作
    componentWillUnmount(){
        //组件销毁时, unsubscribe 取消订阅
        PubSub.unsubscribe('hero');
    }
}
